<template>
  <el-dialog :title="form.id ? '编辑' : '新增'" v-model="visible" :close-on-click-modal="false" draggable>
    <el-form ref="dataFormRef" :model="form" :rules="dataRules" formDialogRef label-width="90px" v-loading="loading">
      <el-row :gutter="24">
        <el-col :span="24" class="mb20">
          <el-form-item label="表单名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入表单名称" />
          </el-form-item>
        </el-col>

        <el-col :span="24" class="mb20" v-for="(item, index) in form.questions" key="index">
          <view>
            <view style="display: flex;align-items: center">
              <view style="margin-right: 10px;width: 120px;font-size: 18px"> 第 {{ index + 1 }} 题</view>
              <el-radio-group style="width: 80%;" v-model="item.type" @change="(val) => {
                handleChange(val, index);
              }">
                <el-radio :key="index" :label="item.value" border v-for="(item, index) in type_Flag">{{ item.label }}
                </el-radio>
              </el-radio-group>

              <view style="display: flex;align-items: center;">
                <el-button type="primary" @click="addQuestion(index)" :disabled="loading">下方新增</el-button>
                <el-button type="danger" @click="delQuestion(index)" :disabled="loading">删除</el-button>
              </view>
            </view>
            <el-input style="margin-top: 10px;" v-model="item.question" placeholder="请输入问题" />
            <el-input style="margin-top: 5px;" v-model="item.data" v-if="item.type == 1" :disabled="true"
              placeholder="简答题无需输入" />
            <el-input style="margin-top: 5px;" v-model="item.data" v-if="item.type == 2" placeholder="请输入选项,每个选项逗号隔开" />
            <el-input style="margin-top: 5px;" v-model="item.data" v-if="item.type == 3" placeholder="请输入选项,每个选项逗号隔开" />
          </view>
        </el-col>

        <el-col :span="24" class="mb20">
          <div style="display: flex;align-items: center;">
            <div>是否全部门</div>
            <el-radio-group v-model="form.isAll" style="margin-left: 20px;">
              <el-radio-button label=0>否</el-radio-button>
              <el-radio-button label=1>是</el-radio-button>
            </el-radio-group>
          </div>
          <div v-if="form.isAll == 0">
            <div class="flex items-center justify-between">
              <div>{{ state.dialog.title }}</div>
              <div class="flex mr-16">
                <el-checkbox label="展开/折叠" @change="handleExpand" />
                <el-checkbox label="全选/不全选" @change="handleSelectAll" />
              </div>
            </div>

            <el-scrollbar class="h-[400px] sm:h-[600px]">
              <el-tree v-loading="loading" ref="menuTree" :data="state.treeData"
                :default-checked-keys="state.checkedKeys" :check-strictly="!checkStrictly" :props="state.defaultProps"
                class="filter-tree" node-key="id" highlight-current show-checkbox />
            </el-scrollbar>
          </div>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="state.dialog.isShowDialog = false">取 消</el-button>
              <el-button type="primary" @click="onSubmit">{{ state.dialog.submitTxt }}</el-button>
            </span>
          </template>
        </el-col>

      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit" :disabled="loading">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="NaireFormDialog">
import { useDict } from '/@/hooks/dict';
import { useMessage } from "/@/hooks/message";
import { getObj, addObj, putObj, deptTree } from '/@/api/backoffice/naireform'
import { rule } from '/@/utils/validate';
import { Ref } from 'vue';
import other from '/@/utils/other';
import { CheckboxValueType } from 'element-plus';
const emit = defineEmits(['refresh']);

const menuTree = ref();
const checkStrictly = ref(true);
// 定义变量内容
const dataFormRef = ref();
const visible = ref(false)
const loading = ref(false)
// 定义字典
const checkedKeys: Ref<any[]> = ref([]);
// 提交表单数据
const form = reactive({
  formId: '',
  name: '',
  isAll: 0,
  pkDept: "",
  questions: [{ type: 1, question: '', data: '' }]
});
const type_Flag = ref([{
  label: '简答',
  value: 1
}, {
  label: '单选',
  value: 2
}, {
  label: '多选',
  value: 3
}])

const state = reactive({
  checkedKeys: [] as any[],
  treeData: [] as any[],
  defaultProps: {
    label: 'name',
    value: 'id',
  },
  roleId: '',
  dialog: {
    isShowDialog: false,
    title: '发布部门',
    submitTxt: '更新',
  },
});

// 定义校验规则
const dataRules = ref({
  name: [{ required: true, message: '表单名称不能为空', trigger: 'blur' }],
})


// 打开弹窗
const openDialog = (id: string) => {
  console.log('id', id);

  state.checkedKeys = [];
  state.treeData = [];
  checkedKeys.value = [];
  visible.value = true
  form.formId = ''
  deptTree().then(res => {
    console.log('deptTree', res.data);
    state.treeData = res.data
    // state.checkedKeys = other.resolveAllEunuchNodeId(state.treeData, checkedKeys.value, []);
  }).then(() => {
    // 重置表单数据
    nextTick(() => {
      dataFormRef.value?.resetFields();
    });

    // 获取naireForm信息
    if (id) {
      form.formId = id
      getnaireFormData(id)
    } else {
      form.questions = [{ type: 1, question: '', data: '' }]
    }
  })

};
const handleExpand = (check: CheckboxValueType) => {
  const treeList = state.treeData;
  for (let i = 0; i < treeList.length; i++) {
    //@ts-ignore
    menuTree.value.store.nodesMap[treeList[i].id].expanded = check;
  }
};

const handleSelectAll = (check: CheckboxValueType) => {
  if (check) {
    menuTree.value?.setCheckedKeys(state.treeData.map((item) => item.id));
  } else {
    menuTree.value?.setCheckedKeys([]);
  }


};
const handleChange = (label, e) => {
  if (label == 1) {
    form.questions[e].data = ''
  }

}
const addQuestion = (index) => {
  let newArr = { type: 1, question: '', data: '' }
  form.questions.splice(index + 1, 0, newArr)
}
const delQuestion = (index) => {
  if (form.questions.length < 0) {
    useMessage().error("只剩一个问题了！");
    return
  }
  form.questions.splice(index, 1)
}
// 提交
const onSubmit = async () => {
  const valid = await dataFormRef.value.validate().catch(() => { });
  if (!valid) return false;
  if (form.isAll == 0) {
    form.pkDept = menuTree.value.getCheckedKeys().join(',')
  } else {
    form.pkDept = ""
  }
  console.log('form', form);
  try {
    loading.value = true;
    form.formId ? await putObj(form) : await addObj(form);
    useMessage().success(form.formId ? '修改成功' : '添加成功');
    visible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg);
  } finally {
    loading.value = false;
  }
};


// 初始化表单数据
const getnaireFormData = (id: string) => {
  // 获取数据
  loading.value = true
  getObj(id).then((res: any) => {
    Object.assign(form, res.data)
    state.checkedKeys = other.resolveAllEunuchNodeId(state.treeData, res.data.depts, []);
  }).finally(() => {
    loading.value = false
  })
};

// 暴露变量
defineExpose({
  openDialog
});
</script>